/* eslint-disable react-hooks/rules-of-hooks */
/*
 * @Author: your name
 * @Date: 2021-10-11 21:00:32
 * @LastEditTime: 2021-11-22 16:18:37
 * @LastEditors: Shentong
 * @Description: 我的评价
 * @FilePath: /distribution/src/pages/collect/index.tsx
 */
import React, { useEffect, useState , useReducer, useCallback, useRef } from 'react';
import Taro, {  usePullDownRefresh, useReachBottom, useDidShow  } from '@tarojs/taro';
import { View } from "@tarojs/components";

import { connect } from 'react-redux'

import { getEvaluateList, delEvaluate } from '@/api/evaluate'

import CommentItem from '@/components/custom/commentItem'

import { showToast } from '@/utils/index';


import NoDataIcon from '@/src/assets/icon/noDataIcon.png'
import NoMore from "@/components/custom/no-more";

import { DefaultAvatar } from '@/src/constants/data'


import styles from './index.module.scss'

const listReducer = (state, action) => {
    switch (action.type) {
        case 'init': return action.payload
        case 'concat': return state.concat(action.payload)
        default: return state
    }
}

const evaluate = () => {
    const [evaluateList, localDispatch] = useReducer(listReducer, [])
    const [pageNo, setPageNo] = useState(1);
    const [pageSize] = useState(10);
    const [evaluateId, setEvaluateId] = useState('')


    const [isLoadFinish, setIsloadFinish] = useState(false)
    const showSkeletonRef =  useRef(true);

    const [showSkeleton, setShowSkeleton] = useState<boolean>(true)

    const dataList = useCallback(() => {
        if(!showSkeletonRef.current) Taro.showLoading({ title: "加载中...", mask: true });
        const params = { pageSize, pageNo}
        
        getEvaluateList(params).then(res => {
            const { data: { records = [], lastPage } = {} } = res
            setIsloadFinish(lastPage)
            const actionType = pageNo === 1 ? 'init' : 'concat'

            localDispatch({ type: actionType, payload: records })

            Taro.hideLoading();
        }).finally(() => {
            setShowSkeleton(false)
            showSkeletonRef.current = false
            Taro.stopPullDownRefresh();
        })
    }, [localDispatch, pageNo, pageSize])

    /**
   * @description 通过id查找数组中某一个，并删除
   */
    //  const delArrByIndex = (addressSId) => {
    //     const findIndexById = addressList.findIndex((item) => item.addressSId === addressSId)
    //     addressList.splice(findIndexById, 1)
  
    //     localDispatch({ type: 'init', payload: addressList })
    //     setMoveIndex(-1)
    //     setCurItem(null)
    //     setDelVoiceConfirm(false)
    //   }

    const delComment = (item) => {
        Taro.showModal({
            title: '温馨提示',
            content: '您是否确认删除此评论？',
            cancelColor: '#666666',
            confirmColor: '#FF9C00',
            success: function (res) {
              if (res.confirm) {
                delEvaluate({ evaluateId: item.evaluateSId }).then(() => {
                    showToast('删除成功',{
                        complete: () => Taro.startPullDownRefresh()
                    })
                })
              }
            }
          })
    }

    // 下拉刷新
    usePullDownRefresh(() => {
        if (pageNo !== 1)  setPageNo(1);
        else dataList()
    });
    useReachBottom(() => {
        !isLoadFinish && setPageNo(pageNo + 1)
    })

    useDidShow(() => {
        pageNo === 1 && dataList()
    })

    useEffect(() => {
        dataList()
    }, [dataList])

    return (
        <View className={styles.appraise}>
            <View>
                
                {
                   evaluateList.map((comment, index) => {
                    return (
                        <CommentItem
                          key={index}
                          userPhoto={comment.userPhoto || DefaultAvatar}
                          createTime={comment.createTime}
                          cellPhone={comment.cellPhone}
                          content={comment.content}
                          isReply={comment.replyContent}
                          showIcon
                          delBtnClick={() => delComment(comment)}
                        />
                      )
                   })
                }
                {evaluateList.length && isLoadFinish ? <NoMore /> : null}
            </View>

            {
                !showSkeleton && !evaluateList.length && (
                    <van-empty description='暂无数据' image={NoDataIcon} />
                )
            }
            
        </View>
    )
}




export default connect((null), dispatch => ({
    dispatch
  }))(evaluate)